package cn.com.yusys.yusp.admin.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;

import cn.com.yusys.yusp.admin.domain.AdminSmDuty;
import cn.com.yusys.yusp.admin.domain.AdminSmUser;
import cn.com.yusys.yusp.admin.repository.mapper.AdminSmDutyMapper;
import cn.com.yusys.yusp.commons.exception.MessageConstants;
import cn.com.yusys.yusp.commons.mapper.CommonMapper;
import cn.com.yusys.yusp.commons.mapper.QueryModel;
import cn.com.yusys.yusp.commons.service.CommonService;
import cn.com.yusys.yusp.commons.util.DateUtil;
import cn.com.yusys.yusp.commons.web.rest.dto.ResultDto;

/**
 * 
 * @项目名称：yusp-admin
 * @类名称：AdminSmDutyService
 * @类描述：
 * @功能描述:岗位管理
 * @创建人：chenlin2@yusys.com.cn
 * @创建时间：2017年12月16日
 * @修改备注：
 * @修改日期 修改人员 修改原因 -------- -------- ----------------------------------------
 * @version 1.0.0
 * @Copyright (c) 2017宇信科技-版权所有
 */
@Service
public class AdminSmDutyService extends CommonService {
    
	private final static Logger logger = LoggerFactory.getLogger(AdminSmDutyService.class);
	
	@Autowired
	private AdminSmDutyMapper mapper;

	public AdminSmDutyService(AdminSmDutyMapper commonMapper) {
		super();
		this.mapper = commonMapper;
	}

	@Override
	protected CommonMapper<?> getMapper() {
		return this.mapper;
	}

	/**
	 * 
	* @方法名称: getDutyByModel
	* @方法描述: 查询岗位
	* @参数与返回说明: 
	* @算法描述:
	 */
	public List<AdminSmDuty> getDutyByModel(QueryModel model) {
		PageHelper.startPage(model.getPage(), model.getSize());
		
        if (model.getCondition().containsKey("dutyName")) {
            if (model.getCondition().get("dutyName") != null && !model.getCondition().get("dutyName").equals("")) {
                model.getCondition().put("dutyName", "%" + model.getCondition().get("dutyName") + "%");
            }
        }
        
		List<AdminSmDuty> list = mapper.getDutyByModel(model);
		PageHelper.clearPage();
		return list;
	}

	/**
	 * 
	* @方法名称: getUserListByModel
	* @方法描述: 查询岗位用户
	* @参数与返回说明: 
	* @算法描述:
	 */
	public List<AdminSmUser> getUserListByModel(QueryModel model) {
		PageHelper.startPage(model.getPage(), model.getSize());
		List<AdminSmUser> list = mapper.getUserListByModel(model);
		PageHelper.clearPage();
		return list;
	}

	/**
	 * 新增岗位
	 */
	public int insert(Object record) {
		AdminSmDuty pool = (AdminSmDuty) record;
		pool.setLastChgDt(DateUtil.formatDateTimeByDef());// 最近跟新时间
		pool.setDutyRemark("");
		logger.info("New job data: [new job: {}] ", pool.getDutyName());
		return this.insert(getMapper(), pool);
	}

	/**
	 * 修改岗位
	 */
	public int update(Object t) {
		AdminSmDuty pool = (AdminSmDuty) t;
		pool.setLastChgDt(DateUtil.formatDateTimeByDef());// 最近跟新时间
		pool.setDutyRemark("");
		logger.info("Job modification data: related data of [modify job: {}]; ", pool.getDutyName());
		return this.update(getMapper(), pool);
	}

	/**
	 * 
	 * @方法名称: deleteBatch
	 * @方法描述: 批量删除
	 * @参数与返回说明:
	 * @算法描述:
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
    public ResultDto<Object> deleteBatch(String[] idStr){
		int n=0;
		Map<String, Object> result=new HashMap<String, Object>();
		ResultDto resultDto = new ResultDto();
		if (idStr != null && idStr.length > 0){
			for (int i = 0; i < idStr.length; i++){
				if (!"".equals(idStr[i])){
					n = n + this.deleteByPrimaryKey(idStr[i]);
				}
			}
			logger.info("Job batch enable [primary key: {}] ", new Object[] {idStr});
			result.put("message", "成功删除"+n+"条数据!");
		}
		resultDto.setMessage((String) result.get("message"));
		resultDto.setData(result);
		return resultDto;
	}

	/**
	 * 
	* @方法名称: useIngFn
	* @方法描述: 批量启用岗位
	* @参数与返回说明: 
	* @算法描述:
	 */
	public ResultDto<Object> useIngFn(String[] idStr, String userId){
		int n = 0;
		Map<String, Object> result=new HashMap<String, Object>();
		ResultDto<Object> resultDto = new ResultDto<>();
		if (idStr != null && /*!"".equals(idStr.toString())*/idStr.length > 0){
			for (int i = 0; i < idStr.length; i++){
				if (!"".equals(idStr[i])){
					Map<String, String> paramMap=new HashMap<String, String>();
					paramMap.put("dutyId", idStr[i]);
					paramMap.put("dutySts", "A");
					paramMap.put("lastChgUsr", userId);
					paramMap.put("lastChgDt", DateUtil.formatDateTimeByDef());
					n=n+this.mapper.updateSts(paramMap);
				}
			}
			logger.info("Job disabled [primary key: {}]" , new Object[] {idStr});
			result.put("message", "成功启动"+n+"条数据!");
		}
		resultDto.setMessage((String) result.get("message"));
		resultDto.setData(result);
		return resultDto;
	}

	/**
	 * 
	* @方法名称: unUseIngFn
	* @方法描述: 批量停用岗位
	* @参数与返回说明: 
	* @算法描述:
	 */
	public ResultDto<Object> unUseIngFn(String[] idStr,String userId) {
		int n = 0;
        List<Object> i18nData = new ArrayList<Object>();
        ResultDto<Object> resultDto = new ResultDto<Object>();
      //modify by Cytus_ at 20180904 修改sonar扫描出现的bug， !"".equals(idStr.toString())语句无意义，根据上下文修改为idStr.length > 0
		if (idStr != null && /*!"".equals(idStr.toString())*/idStr.length > 0) {
		    int count = 0;
			for (int i = 0; i < idStr.length; i++) {
				if (!"".equals(idStr[i])) {
				    int num = this.mapper.getUserByDuty(idStr[i]);
				    if(num>0){
                        count++;
                    }else{
                        Map<String, String> paramMap=new HashMap<String, String>();
                        paramMap.put("dutyId", idStr[i]);
                        paramMap.put("dutySts", "I");
                        paramMap.put("lastChgUsr", userId);
                        paramMap.put("lastChgDt", DateUtil.formatDateTimeByDef());
                        n=n+this.mapper.updateSts(paramMap);
                        logger.info("Job disabled [primary key: {}] ", idStr[i]);
                    }
				}

			}
            if(count==0) {
//                result.put("message", "成功停用"+n+"条数据!");
            	resultDto.setCode(0);
            	resultDto.setMessage("成功停用"+n+"条数据!");
            	i18nData.add(n);
            }else {
//                result.put("message", "成功停用"+n+"条数据,有"+count+"条数据由于存在用户数据，无法停用!");
            	resultDto.setCode(0);
            	resultDto.setMessage("成功停用"+n+"条数据,有"+count+"条数据由于存在用户数据，无法停用!");
            	i18nData.add(n);
            	i18nData.add(count);
            }
		}
		resultDto.setI18nData(i18nData);
		return resultDto;
	}


	/**
	 * 
	* @方法名称: checkDutyCode
	* @方法描述: 检查岗位编号是否重复
	* @参数与返回说明: 
	* @算法描述:
	 */
	public int checkDutyCode(String dutyCde){
		return this.mapper.checkDutyCode(dutyCde);
	}
	
	/**
	 * 
	* @方法名称: checkHasUser
	* @方法描述: 检查岗位下是否存在用户
	* @参数与返回说明: 
	* @算法描述:
	 */
	public int checkHasUser(String dutyId){
		String [] dutyIds = dutyId.split(",");
		return this.mapper.checkHasUser(dutyIds);
	}
}
